package com.xzzz.expand.es.core;

import com.xzzz.expand.es.core.common.EsException;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.AnalyzeRequest;
import org.elasticsearch.client.indices.AnalyzeResponse;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;

@Slf4j
public class EsSearchManager extends EsIndicesManager {

    public EsSearchManager(RestHighLevelClient restHighLevelClient, EsProperties esProperties) {
        super(restHighLevelClient, esProperties);
    }

    /**
     * 原生搜索功能, 查询条件由调用方构造, 只做最基础的ES查询调用
     *
     * @param index index
     * @param searchSource 搜索条件
     * @return 搜索结果
     */
    public SearchResponse search(String index, SearchSourceBuilder searchSource) {
        SearchRequest request = new SearchRequest(index).source(searchSource);
        try {
            // 滚动ID
            return client.search(request, RequestOptions.DEFAULT);
        } catch (ElasticsearchStatusException ex) {
            esExceptionSuppose(ex);
            throw new EsException("ES处理错误:" + ex.getMessage());
        } catch (Exception e) {
            throw new EsException(String.format("查询失败[%s]: %s", e.getClass().getName(), e.getMessage()));
        }
    }

    /**
     * 分词器分词
     * @param analyzer 分词器
     * @param text 分词内容
     * @return 分词结果
     */
    public AnalyzeResponse analyze(String analyzer, String text) {
        AnalyzeRequest request = AnalyzeRequest.withGlobalAnalyzer(analyzer,text);
        try {
            return client.indices().analyze(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            throw new EsException("查询失败:" + e.getMessage());
        } catch (Exception e) {
            throw new EsException("查询失败:" + e.getMessage());
        }
    }
}
